package cn.biplam.front.component.view.systemManage.datasource;

import cn.biplam.common.client.DataFilter;
import cn.biplam.common.client.Operator;
import cn.biplam.common.client.OperatorResult;
import cn.biplam.common.opcode.mdManage.BmCode.BmMdThemeCode;
import cn.biplam.common.opcode.mdManage.DwCode.DwMdThemeCode;
import cn.biplam.common.opcode.mdManage.SrcCode.SrcMdThemeCode;
import cn.biplam.common.opcode.mdManage.TypeCode.DbSourceCode;
import cn.biplam.common.struc.MdStruc;
import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.UserInfo;
import cn.biplam.front.component.AjxResponse;
import cn.biplam.front.component.data.common.ButtonComp;
import cn.biplam.front.component.data.common.CaptionComp;
import cn.biplam.front.component.view.systemManage.datasource.callback.DbSourceDbTypeCallBack;
import cn.biplam.front.component.view.systemManage.datasource.callback.DbSourceModelTypeCallBack;
import cn.biplam.front.component.view.systemManage.datasource.callback.DbSourceNameCallBack;
import cn.biplam.front.component.view.systemManage.datasource.callback.DbSourceoperatorCallBack;
import cn.biplam.front.html.HtmlDiv;
import cn.biplam.front.html.HtmlText;
import cn.biplam.front.html.HtmlValue;
import cn.biplam.front.html.base.HtmlWindow;
import cn.biplam.front.html.base.Const.Float_Type;
import cn.biplam.front.html.base.Const.Window_Event;
import cn.biplam.front.htmlscript.script.AjxScript;
import cn.biplam.front.htmlscript.script.AjxScript.Is_SubMitData;
import cn.biplam.front.template.base.ButtonGroup;
import cn.biplam.front.template.control.Confirm;
import cn.biplam.front.template.control.FlatTable;
import cn.biplam.front.template.control.FlowTable;
import cn.biplam.front.template.control.table.TablePropertys;
import cn.biplam.front.template.pageFrame.mdManage.MdObject;
import cn.biplam.front.template.pageFrame.mdManage.MdPage;
import cn.biplam.front.template.pageFrame.mdManage.MdTable;

/**
 * 数据源管理主页面
 * @author WangSong 2009-7-21下午04:43:34
 * @version 1.0
 */
public class DataSourceMain extends AjxResponse {

	public static final String cId="8201";
	public static final String aId_main="820101";
	public static final String aId_delete="820102";
	public static final String aId_delete_opt="820103";
	
	@Override
	protected HtmlWindow ajxGet() throws ErrorMessage {
		if(aId_main.equals(actionId)){
			return getMainPage(mUser, sHomeUrl);
		}if(aId_delete.equals(actionId)){
			return getDelete(recordId,mUser);
		}if(aId_delete_opt.equals(actionId)){
			return getDeleteOpt(recordId,mUser);
		}else{
			throw new ErrorMessage("actionid is not found:"+actionId+"!");
		}
	}
	
	/**
	 * 取数据源管理的主页面
	 * @param mUser 用户信息
	 * @return HtmlWindow
	 * @throws ErrorMessage 
	 */
	private HtmlWindow getMainPage(UserInfo mUser,String sHomeUrl) throws ErrorMessage{
		MdPage page = new MdPage(cId,sHomeUrl,mUser);
		/** 设置界面标题 */
		page.setTitleDesc(CaptionComp.get(mUser, "293"));
		/** 设置界面标题logo */
		page.setTitleLogo("/images/sm_ds.gif");
		
		String domainID = cId+"1";
		String tablePageID = domainID + "t";
		MdObject mdo = new MdObject(domainID);
		MdTable table = new MdTable(tablePageID, recordId);
		table.putObjectCol(getTable(mUser, tablePageID+"2"));
		mdo.putTable(table.get());
		/** 放入操作按钮组件 */
		mdo.putOperator(getOperators(recordId, mUser));

		page.putManage(mdo.get());
		
		return page.get();
	}
	
	/**
	 * 主页面数据源信息表格
	 * @param mUser 用户信息
	 * @return
	 * @throws ErrorMessage 
	 */
	private HtmlWindow getTable(UserInfo mUser,String pageID) throws ErrorMessage{
		HtmlWindow table = new HtmlDiv();
		
		DataFilter filter=new DataFilter();
		OperatorResult sr=Operator.get(DbSourceCode.Select_All, mUser.getUserID(), filter);
		if(sr!=null && !sr.isNull()){
			/** 表主键 */
			String mainKey=MdStruc.DbSourStruc.DB_SOURCE_ID;
			/** 表格列对应字段名 */
			String[] tableFields={MdStruc.DbSourStruc.DB_SOURCE_ID,
								  MdStruc.DbSourStruc.DB_SOURCE_NAME,
								  MdStruc.DbSourStruc.DB_TYPE_ID,
								  MdStruc.DbSourStruc.IP,
								  MdStruc.DbSourStruc.PORT,
								  MdStruc.DbSourStruc.DB_SOURCE_SID,
								  MdStruc.DbSourStruc.MAIN_DB,
								  MdStruc.DbSourStruc.USRE_NAME,
								  MdStruc.DbSourStruc.MODEL_TYPE,
								  "operator"};
			/** 表格列类型 */
			TablePropertys.Col_Content_Type[] fieldsType={
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.NAME_TEXT,
					TablePropertys.Col_Content_Type.BUTTON
			};
			/** 设置列标题 数据源ID,数据源名称,数据库类型,主机名/IP,端口,数据库实例名,数据库名称,用户名,操作*/
			String[] tableColTitles={CaptionComp.get(mUser,"294"),
									 CaptionComp.get(mUser,"58"),
									 CaptionComp.get(mUser,"53"),
									 CaptionComp.get(mUser,"295"),
									 CaptionComp.get(mUser,"296"),
									 CaptionComp.get(mUser,"61"),
									 CaptionComp.get(mUser,"55"),
									 CaptionComp.get(mUser,"297"),
									 "模型类型",
									 CaptionComp.get(mUser,"20")};
			TablePropertys property=new TablePropertys(tableFields,fieldsType,tableColTitles,sHomeUrl,mUser);
		
			/** 设置数据源名称*/
			this.setDbName(property);
			/** 设置任务状态*/
			this.setDbType(property);
			/** 设置模型类型*/
			this.setModelType(property);	
			/** 设置操作按钮*/
			this.setOperator(property);
			
			/** 创建表对象 */
			FlowTable st=new FlowTable(pageID,mainKey,property); 
			/** 将数据集放入表格 */
			st.put(sr);
			table.put(st.get());
		}else{
			FlatTable ft=new FlatTable(pageID,"");
			HtmlWindow text =new HtmlText(null,null,"无数据源信息");
			text.setStyle("text-align","center");
			ft.putTh(CaptionComp.get(mUser,"294"),0,0);
			ft.putTh(CaptionComp.get(mUser,"58"),0,1);
			ft.putTh(CaptionComp.get(mUser,"53"),0,2);
			ft.putTh(CaptionComp.get(mUser,"295"),0,3);
			ft.putTh(CaptionComp.get(mUser,"296"),0,4);
			ft.putTh(CaptionComp.get(mUser,"61"),0,5);
			ft.putTh(CaptionComp.get(mUser,"55"),0,6);
			ft.putTh(CaptionComp.get(mUser,"297"),0,7);
			ft.putTh(CaptionComp.get(mUser,"20"),0,8);
			ft.putTd(text, 1, 0,"9","4");
			table.put(ft.get());
		}
		return table;
	}
	
	/**
	 * 设置数据源名称
	 * @param property
	 * @throws ErrorMessage
	 */
	private void setDbName(TablePropertys property) throws ErrorMessage{
		property.setCallBack(MdStruc.DbSourStruc.DB_SOURCE_NAME, new DbSourceNameCallBack());
	}
	
	/**
	 * 设置模型类型
	 * @param property
	 * @throws ErrorMessage
	 */
	private void setModelType(TablePropertys property) throws ErrorMessage{
		property.setCallBack(MdStruc.DbSourStruc.MODEL_TYPE, new DbSourceModelTypeCallBack());
	}
	
	/**
	 * 设置数据库类型
	 * @param property
	 * @throws ErrorMessage
	 */
	private void setDbType(TablePropertys property) throws ErrorMessage{
		property.setCallBack(MdStruc.DbSourStruc.DB_TYPE_ID, new DbSourceDbTypeCallBack());
	}
	
	
	/**
	 * 设置操作按钮
	 * @param property
	 * @throws ErrorMessage
	 */
	private void setOperator(TablePropertys property) throws ErrorMessage{
		/**设置操作按钮*/
		property.setCallBack("operator", new DbSourceoperatorCallBack());
		/** 设置动作*/
		property.setColAction("operator",Window_Event.OnClick,TablePropertys.Action_Type.POP_SUBMIT_PR,
				aId_delete,null);
		property.setColAction("operator",Window_Event.OnClick,TablePropertys.Action_Type.POP_SUBMIT_PR,
				DataSourceModify.Modify_DbSource,null);
	}
	
	/**
	 * 生成仓库对象维护操作按钮并绑定按钮事件
	 * @param mUser
	 * @return
	 * @throws ErrorMessage
	 */
	private HtmlWindow getOperators(String recordId,UserInfo mUser) throws ErrorMessage{
		ButtonGroup operatorButtons=new ButtonGroup("",Float_Type.Right);
		if(recordId!=null){
			HtmlWindow refreshBt=ButtonComp.get(mUser, "200");
			refreshBt.bind(Window_Event.OnClick, AjxScript.getA(cId,aId_main,null));
			operatorButtons.put(refreshBt);
			HtmlWindow addBt=ButtonComp.get(mUser, "25");
			/** 放入隐藏参数信息*/
			addBt.put(new HtmlValue(cId+"r",cId+"r",recordId));
			addBt.bind(Window_Event.OnClick,AjxScript.getPr(cId,DataSourceAdd.Add_DbSource,Is_SubMitData.NoSubmit,null));
			operatorButtons.put(addBt);
			
			
		}
		return operatorButtons.get();
	}
	
	/**
	 * 删除数据源
	 * @param recordId  数据源id
	 * @param mUser     用户信息
	 * @return  HtmlWindow
	 * @throws ErrorMessage 
	 */
	private HtmlWindow getDelete(String recordId,UserInfo mUser) throws ErrorMessage{
		//获取删除数据源信息
		DataFilter filter=new DataFilter();
		filter.put(MdStruc.DbSourStruc.DB_SOURCE_ID, recordId);
		OperatorResult sr = Operator.get(DbSourceCode.Select_By_ID, mUser.getUserID(), filter);
		StringBuilder sp = new StringBuilder();
		if(TOOLS.exist(sr)){
			sp.append("确认删除'");
			sp.append(sr.getValue(MdStruc.DbSourStruc.DB_SOURCE_NAME));
			sp.append("'?");
		}
		//创建删除界面
		Confirm delete = new Confirm(sp.toString(),recordId);
		//绑定删除按钮提交动作
		delete.bind(aId_delete_opt);
		return delete.get();
	}
	
	/**
	 * 删除数据源
	 * @param recordId
	 * @param mUser
	 * @return
	 * @throws ErrorMessage 
	 */
	private HtmlWindow getDeleteOpt(String recordId,UserInfo mUser) throws ErrorMessage{
		HtmlWindow delete = new HtmlDiv();
		if(!this.dbSourceIsUsed(recordId, mUser)){
			DataFilter filter=new DataFilter();
			filter.put(MdStruc.DbSourStruc.DB_SOURCE_ID, recordId);
			Operator.get(DbSourceCode.Delete_By_ID, mUser.getUserID(), filter);
		}else{
			delete.bind("alert('数据源id被引用,不能删除');");
		}
		/** 绑定刷新父页面脚本*/
		delete.bind(AjxScript.getA(DataSourceMain.cId,DataSourceMain.aId_main,"refresh"));
		return delete;
	}
	
	/**
	 * 检查数据源是否被引用 true:被引用 ,false:没被引用
	 * @param recordId  
	 * @return
	 * @throws ErrorMessage 
	 */
	private boolean dbSourceIsUsed(String recordId,UserInfo mUser) throws ErrorMessage{
		/**数据源是否在 目前只判断数据探查用到的表*/
		/** 取数据源所属模型类型*/
		String modelType = null;
		String actionTheme = null;
		DataFilter filterds=new DataFilter();
		filterds.put(MdStruc.DbSourStruc.DB_SOURCE_ID, recordId);
		OperatorResult srds = Operator.get(DbSourceCode.Select_By_ID, mUser.getUserID(), filterds);
		if(TOOLS.exist(srds)){
			modelType = srds.getValue(MdStruc.DbSourStruc.MODEL_TYPE);
			if("1".equals(modelType)){
				actionTheme = SrcMdThemeCode.Get_Theme_By_Dssid;
			}else if("2".equals(modelType)){
				actionTheme = BmMdThemeCode.Get_Theme_By_Dssid; 
			}else if("3".equals(modelType)){
				actionTheme = DwMdThemeCode.Get_Theme_By_Dssid;
			}
		}
		/** 判断源对象主题表是否用到此数据源*/
		DataFilter filter = new DataFilter();
		filter.put(MdStruc.SrcMdThemeStruc.dsID, recordId);
		try{
			OperatorResult  sr = Operator.get(actionTheme, mUser.getUserID(), filter);
			if(TOOLS.exist(sr)){
				return true;
			}
		}catch(ErrorMessage e){
			StringBuilder sb = new StringBuilder();
			e.getDescription(sb);
			if(sb!=null && sb.indexOf("java.lang.ClassNotFoundException")!=-1){
				DEBUG.println("DataSource delete Error,actionTheme may not publish!");
				return true;
			}else{
				throw e;
			}
		}
		return false;
	}

}
